package middleware

import (
	"errors"
	"haiqiu-go-admin/result"
	"log"
	"net/http"
	"runtime/debug"
)

// 统一异常处理
func Recover() Middleware {
	return func(handlerFunc http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				e := recover()
				if e != nil {
					var err error
					log.Printf("panic：%v\n", e)
					debug.PrintStack()
					switch v := e.(type) {
					case error:
						err = v
					default:
						err = errors.New(e.(string))
					}
					result.Fail(w, r, err)
					return
				}
			}()
			//加载完 defer recover，继续后续接口调用
			handlerFunc(w, r)
		}
	}
}
